package gov.nist.healthcare.testframework.communication;

import gov.nist.healthcare.testframework.TestFramework;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import javax.net.SocketFactory;
import org.apache.log4j.Logger;

public class CommunicationUtils {

    private static final Logger logger = Logger.getLogger(CommunicationUtils.class.getName());

    /**
     * Send data by using the Socket passed in parameter.
     * 
     * @param socket
     * @param data
     * @throws IOException
     */
    public static void send(Socket socket, String data) throws IOException {
        logger.debug(String.format("Send from %s to %s",
                socket.getInetAddress(), socket.getRemoteSocketAddress()));
        PrintWriter out = new PrintWriter(socket.getOutputStream(), true);
        out.write(data);
        out.flush();
        logger.debug("Send done");
    }

    /**
     * Create a Socket.
     * 
     * @param ip
     * @param secure
     * @return a new Socket
     * @throws IOException
     */
    public static Socket createSocket(InetSocketAddress ip, boolean secure)
            throws IOException {
        Socket socket = null;
        if (!secure) {
            socket = new Socket(ip.getAddress(), ip.getPort());
        } else {
            SocketFactory sf = TestFramework.getInstance().getSSLContext().getSocketFactory();
            socket = sf.createSocket(ip.getAddress(), ip.getPort());
        }
        socket.setSoTimeout(60000);
        return socket;
    }

}
